
package com.kugou.game.sdk.protocol;

import com.kugou.framework.base.AppException;
import com.kugou.framework.base.LogUtil;
import com.kugou.framework.http.KGHttpClient;
import com.kugou.framework.http.ResponsePackage;
import com.kugou.framework.utils.UrlEncodeUtil;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.entity.MessageHttpResponse;
import com.kugou.game.sdk.entity.MessageInfo;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.ProtocolCmd;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.text.TextUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * 描述:解析http推送消息
 * 
 * @author allenli
 * @since 2014-8-13 下午12:42:23
 */
public class MessageTask {
    private ArrayList<String> mCmdList = new ArrayList<String>();

    public MessageHttpResponse request(Context context, long appid, String appkey, int gameid,
            int merchantId, int sdkversioncode, String sdkversionname, int gametype,
            String mesVersionId) {
        ArrayList<HashMap<String, Object>> requestParams = new ArrayList<HashMap<String, Object>>();
        // 填充参数，key-value。key是接口要求传的变量名称
        HashMap<String, Object> params = new HashMap<String, Object>();
        long time = System.currentTimeMillis() / 1000;
        params.put("cmd", ProtocolCmd.CMD_MESSAGE_PUSH);
        params.put("mesversionid", mesVersionId);
        params.put("unixtime", time);
        // 生成请求包
        HttpBaseRequestPackage requestPackage = new MessageRequestPackage(context, appid, appkey,
                gameid, merchantId, sdkversioncode, sdkversionname, gametype);
        // 生成响应包
        ResponsePackage responsePackage = new MessageResponse();
        // 生成响应类
        MessageHttpResponse appsHttpResponse = new MessageHttpResponse();
        requestParams.add(params);
        requestPackage.setRequestParams(requestParams);
        mCmdList.add(ProtocolCmd.CMD_MESSAGE_PUSH);
        try {
            KGHttpClient.request(requestPackage, responsePackage);
            // 响应类赋值
            responsePackage.getResponseData(appsHttpResponse);
            // 返回响应类
            return appsHttpResponse;
        } catch (AppException e) {
        }
        return null;
    }

    class MessageRequestPackage extends HttpBaseRequestPackage {
        Context context;

        long appid;

        String appkey;

        int gameid;

        int merchantId;

        int sdkversioncode;

        String sdkversionname;

        int gametype;

        MessageRequestPackage(Context context, long appid, String appkey, int gameid,
                int merchantId, int sdkversioncode, String sdkversionname, int gametype) {
            this.context = context.getApplicationContext();
            this.appid = appid;
            this.appkey = appkey;
            this.merchantId = merchantId;
            this.gameid = gameid;
            this.sdkversioncode = sdkversioncode;
            this.sdkversionname = sdkversionname;
            this.gametype = gametype;
        }

        @Override
        public String getGetRequestParams() {
            StringBuilder getParams = new StringBuilder();
            /*--公共参数--*/
            // 固定参数
            try {
                getParams.append("?r=main");
                // merchantid
                getParams.append("&merchantid=" + merchantId);
                // appid
                getParams.append("&appid=" + appid);
                // gameid
                getParams.append("&gameid=" + gameid);
                // serverid
                getParams.append("&serverid=" + 1);
                // imei
                String imei = AppUtil.getMachineSN(context);
                getParams.append("&imei=" + UrlEncodeUtil.encode(imei, "UTF-8"));
                // 渠道号
                getParams.append("&channelid=" + 1);
                // 平台，1为android，2为ios官方版，3为ios越狱版
                getParams.append("&platform=" + 1);
                // 手机型号
                getParams
                        .append("&model=" + UrlEncodeUtil.encode(AppUtil.getPhoneModel(), "UTF-8"));
                // 网络类型，1=wifi，2=2g，3=3g，4=4g,5=未知
                getParams.append("&nettype=" + AppUtil.getNetworkType(context));
                // uuid
                getParams.append("&uuid="
                        + UrlEncodeUtil.encode(AppUtil.getKugouUUID(context), "UTF-8"));
                // mid
                getParams.append("&mid="
                        + UrlEncodeUtil.encode(AppUtil.getKugouMID(context), "UTF-8"));
                // SDK版本名称
                getParams.append("&clientversionname="
                        + UrlEncodeUtil.encode(sdkversionname, "UTF-8"));
                // SDK版本号
                getParams.append("&clientversioncode=" + sdkversioncode);
                // 游戏版本名称
                getParams.append("&appversion="
                        + UrlEncodeUtil.encode(AppUtil.getVersionName(context), "UTF-8"));
                // 游戏版本号
                getParams.append("&appversioncode=" + AppUtil.getVersionCode(context));
                // 客户端类型(0:游戏sdk，1:hi游sdk，2:h5sdk)
                getParams.append("&clienttype=" + 0);
                // sdk类型，0:网游、1:单机
                getParams.append("&sdktype=" + gametype);
                // 系统版本
                getParams.append("&sysversion="
                        + UrlEncodeUtil.encode(AppUtil.getSysVersionName(), "UTF-8"));
                User user = UserManager.getInstance().getCurrentUserInternal();
                // Sdk服务端生成verifytoken，用户游戏对接服务端之间的登录验证
                getParams.append("&verifytoken="
                        + UrlEncodeUtil.encode((user == null ? "" : user.getToken()), "UTF-8"));
                // 酷狗用户登录令牌
                String kgtoken = user == null ? "" : user.getKugouToken();
                getParams.append("&kgtoken=" + UrlEncodeUtil.encode(kgtoken, "UTF-8"));
                // 来源 1 酷狗SDK 2 游戏中心
                getParams.append("&sourcetype=" + 1);
                // 用户名
                String username = user == null ? "" : user.getAccountName();
                getParams.append("&username=" + UrlEncodeUtil.encode(username, "UTF-8"));

                /*--每个接口特有参数--*/
                if (mRequestParams != null && mRequestParams.size() >= 0) {
                    int size = mRequestParams.size();
                    JSONArray jsonArray = new JSONArray();
                    JSONObject jsonObj;

                    for (int i = 0; i < size; i++) {
                        HashMap<String, Object> cmdParams = mRequestParams.get(i);
                        jsonObj = new JSONObject();
                        final Set<String> keys = cmdParams.keySet();
                        for (String key : keys) {
                            jsonObj.put(key, cmdParams.get(key));
                        }
                        jsonArray.put(jsonObj);
                    }

                    String jsonStr = jsonArray.toString();
                    getParams.append("&jsonparam=" + UrlEncodeUtil.encode(jsonStr, "UTF-8"));
                    getParams.append("&sign="
                            + AppUtil.getSign(merchantId, appid, appkey, username, kgtoken, imei,
                                    sdkversioncode));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            String str = getParams.toString();
            return str;
        }
    }

    class MessageResponse extends HttpBaseResponsePackage<MessageHttpResponse> {

        @Override
        protected void handleResponse(MessageHttpResponse response, String responseJsonStr) {
            try {
                LogUtil.d("response", "MessageTask:" + responseJsonStr);
                if (TextUtils.isEmpty(responseJsonStr)) {
                    return;
                }
                JSONArray responseArray = new JSONArray(responseJsonStr.trim());
                int size = responseArray.length();
                for (int i = 0; i < size; i++) {
                    if (i >= mCmdList.size()) {
                        break;
                    }
                    JSONObject jsonResp = responseArray.getJSONObject(i);
                    String cmd = jsonResp.optString("cmd");
                    response.setCode(jsonResp.optString("code"));
                    response.setMessage(jsonResp.optString("message"));
                    response.setPrompt(jsonResp.optString("prompt"));
                    if (jsonResp.optInt("code") != 1) {
                        continue;
                    }
                    if (jsonResp.isNull("data")) {
                        continue;
                    }
                    if (ProtocolCmd.CMD_MESSAGE_PUSH.equalsIgnoreCase(cmd)) {
                        JSONObject jsonResult = jsonResp.getJSONObject("data");
                        if (jsonResult != null) {
                            response.setMesVersionId(jsonResult.getString("mesversionid"));
                            if (jsonResult.isNull("list"))
                                return;
                            JSONArray listArray = jsonResult.getJSONArray("list");
                            // 将消息列表的json字符串存入
                            List<String> msgJsonStr = new ArrayList<String>();
                            List<MessageInfo> messageInfoList = new ArrayList<MessageInfo>();
                            for (int j = 0; j < listArray.length(); j++) {
                                JSONObject itemObj = listArray.getJSONObject(j);
                                msgJsonStr.add(itemObj.toString());
                                MessageInfo info = new MessageInfo();
                                info.setContent(itemObj.getString("content"));
                                info.setDownloadUrl(itemObj.getString("downloadurl"));
                                info.setImageUrl(itemObj.getString("imageurl"));
                                info.setMessageId(itemObj.getString("messageid"));
                                info.setPackagename(itemObj.getString("packagename"));
                                info.setTitle(itemObj.getString("title"));
                                info.setType(itemObj.getString("type"));
                                messageInfoList.add(info);
                            }
                            response.setMessageInfoListJson(msgJsonStr);
                            response.setMessageInfoList(messageInfoList);
                        }
                    }
                    response.setOk(true);

                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
